package Creational.Singleton;

import org.testng.annotations.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeUnit;

// 懒加载
// 静态内部类只有在使用的时候才会加载  JVM 保证 一个类只加载一次 所以是线程安全的
public class InnerClassDemo {

	@Test(description = "多线程测试")
	public void t1(){
		for (int i = 0; i < 5; i++) {
			new Thread(() -> System.out.println(InnerClass.getInstance().hashCode())).start();
		}
	}

	@Test(description = "通过反射创建实例")
	public void t2() throws Exception {
		Constructor<InnerClass> declaredConstructor = InnerClass.class.getDeclaredConstructor();
		declaredConstructor.setAccessible(true);
		InnerClass innerClass1 = declaredConstructor.newInstance();
		InnerClass innerClass2 = declaredConstructor.newInstance();
		System.out.println(innerClass1 == innerClass2);
	}
}

class InnerClass {

	private InnerClass() {
		if (InnerClassHolder.instance != null) {
			throw new RuntimeException("单例模式 不允许多实例");
		}
	}

	private static class InnerClassHolder {
		private static final InnerClass instance = new InnerClass();
	}

	public static InnerClass getInstance() {
		return InnerClassHolder.instance;
	}

}
